﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAPbobsCOM;
using System.Collections;
using BoAddonBiz_FreightForwarder.BusinessBase;
using BoAddonBiz_FreightForwarder.Cost.Bo;
using System.Xml;
using SAPbouiCOM;

namespace BoAddonBiz_FreightForwarder
{
    /// <summary>
    /// 制作费用（业务单按钮触发显示该窗体）——comment by Webb.Wen
    /// </summary>
    [ControlB1FormAttribute(IsNew = true, FormType = B1FormTypes.ado_AVA_FF_CreateCost)]
    public class B1Form_CreateCost : SAPBoAddon.B1Form
    {
        internal static OrderLines B1Order = new OrderLines();
        Dictionary<string, string> Dic_ColField = new Dictionary<string, string>();
        string FormUID_BusinessOperation = string.Empty;
        Dictionary<string, double> Dic_BoxTypeQty;
        private string[] ItemGroups_Rece = new string[] { "67", "68", "DSend", "DApp", "mtx_0" };
        private string[] ItemGroups_Pay = new string[] { "43", "44", "CSend", "CApp", "mtx_1" };
        string BusinessType = string.Empty;
        public B1Form_CreateCost()
        {
            frm_ChooseFormListEvent += new SAPBoAddon.IB1FormEvents.B1ChooseFormListEventEventHandler(B1Form_CreateCost_frm_ChooseFormListEvent);
            frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_CreateCost_frm_ItemEvent);
            frm_FormDataEvent += new SAPBoAddon.IB1FormEvents.B1FormDataEventEventHandler(B1Form_CreateCost_frm_FormDataEvent);
        }

        #region 继承基类
        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {
        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            FormSetting.FormType = B1FormTypes.ado_AVA_FF_CreateCost;
            FormSetting.FormFileName = "AVA_FF_CreateCostForm.srf";
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
            this.CurrentForm.Freeze(true);
            B1Order.Clear();
            this.MatrixColumns_DataBind("mtx_0");
            this.InitializeAllCombobox();
            #region 基于业务单
            if (InitPar.FatherFormUID.StartsWith(B1FormTypes.ado_AVA_FF_BusinessOperation)
                || InitPar.FatherFormUID.StartsWith(B1FormTypes.ado_AVA_SE_BusinessOperation)
                || InitPar.FatherFormUID.StartsWith(B1FormTypes.ado_AVA_LN_BusinessOperation)
                || InitPar.FatherFormUID.StartsWith(B1FormTypes.ado_AVA_OR_BusinessOperation)
                )
            {
                Dic_BoxTypeQty = new Dictionary<string, double>();
                SBOApp.StatusBar.SetText("正在加载数据项，请稍后...", SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Warning);
                this.CurrentForm.DataSources.UserDataSources.Item("ParentUID").Value = InitPar.FatherFormUID;
                this.CurrentForm.Items.Item("Radio_In").Click();
                FormUID_BusinessOperation = InitPar.FatherFormUID;
                SAPbouiCOM.Form FatherForm = SBOApp.Forms.Item(InitPar.FatherFormUID);
                SAPbouiCOM.DBDataSource dbds_Operation = null;
                IEnumerator enumerator = FatherForm.DataSources.DBDataSources.GetEnumerator();
                string Status_BP = string.Empty;
                string Status_Rece = string.Empty;
                string Status_Pay = string.Empty;
                while (enumerator.MoveNext())
                {
                    if ((enumerator.Current as SAPbouiCOM.DBDataSource).TableName.EndsWith("_OBNO"))
                    {
                        dbds_Operation = enumerator.Current as SAPbouiCOM.DBDataSource;
                    }
                }
                Status_BP = dbds_Operation.GetValue("U_Status", dbds_Operation.Offset).Trim(); //业务单状态
                Status_Rece = dbds_Operation.GetValue("U_ReceApproved", dbds_Operation.Offset).Trim();
                Status_Pay = dbds_Operation.GetValue("U_PayApproved", dbds_Operation.Offset).Trim();
                #region 单据状态控制
                if (new string[] { "R", "C", "D" }.Contains<string>(Status_BP))  //, "A" 已审核 状态也不可编辑 by WangPeng 2012年9月27日 13:33:45
                {
                    if (new string[] { "C", "D" }.Contains<string>(Status_BP))
                    {
                        SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, new string[] { "57", "Radio_In", "Radio_Out", "67", "68", "43", "44", "1", "DSend", "DApp", "CSend", "CApp", "mtx_0", "mtx_1", "DAppC", "CAppC" }, false); // "DCheck", "DCancel","CCheck", "CCancel", 这些控件已删除 by WangPeng2012年9月27日 13:34:20
                    }
                    else
                    {
                        SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, new string[] { "57", "Radio_In", "Radio_Out", "67", "68", "43", "44", "1", "DSend", "DApp", "CSend", "CApp", "mtx_0", "mtx_1" }, false); // "DCheck", "DCancel","CCheck", "CCancel", 这些控件已删除 by WangPeng2012年9月27日 13:34:20
                    }
                }
                else
                {
                    if (Status_BP == "P")
                        SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, new string[] { "DApp", "CApp", "DAppC", "CAppC" }, false); // "DCheck", "DCancel","CCheck", "CCancel", 这些控件已删除 by WangPeng2012年9月27日 13:34:20
                    if (Status_Rece == "Y")
                    {
                        SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, ItemGroups_Rece, false);
                    }
                    else
                    {
                        SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, "DAppC", false);
                    }
                    if (Status_Pay == "Y")
                    {
                        SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, ItemGroups_Pay, false);
                    }
                    else
                    {
                        SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, "CAppC", false);
                    }
                }
                #endregion
                this.CurrentForm.DataSources.UserDataSources.Item("BPTable").ValueEx = dbds_Operation.TableName;
                #region 海运操作 - 取箱型填充到计量单位
                //海运 取箱型填充到计量单位 
                if (InitPar.FatherFormUID.StartsWith(B1FormTypes.ado_AVA_SE_BusinessOperation))
                {
                    if (dbds_Operation.GetValue("U_ContainerType", dbds_Operation.Offset).Trim() == "1")//FCL
                    {
                        this.GetSEBusinessOperationFCL(dbds_Operation.GetValue("DocEntry", dbds_Operation.Offset).Trim());
                    }
                }
                #endregion
                #region 计量单位带业务单对应数据
                if (Dic_BoxTypeQty.ContainsKey("PCS"))
                {
                    Dic_BoxTypeQty["PCS"] = Convert.ToDouble(dbds_Operation.GetValue("U_Quantity", dbds_Operation.Offset).Trim());
                }
                else
                {
                    Dic_BoxTypeQty.Add("PCS", Convert.ToDouble(dbds_Operation.GetValue("U_Quantity", dbds_Operation.Offset).Trim()));
                }
                if (Dic_BoxTypeQty.ContainsKey("CBM"))
                {
                    Dic_BoxTypeQty["CBM"] = Convert.ToDouble(dbds_Operation.GetValue("U_Volume", dbds_Operation.Offset).Trim());
                }
                else
                {
                    Dic_BoxTypeQty.Add("CBM", Convert.ToDouble(dbds_Operation.GetValue("U_Volume", dbds_Operation.Offset).Trim()));
                }

                #endregion

                (this.CurrentForm.Items.Item("mtx_0").Specific as SAPbouiCOM.Matrix).Columns.Item("col_Unit").ValidValues.Add("", "");

                string BaseType = GetBoType(InitPar.FatherFormUID);
                BusinessType = BaseType;
                string BaseEntry = dbds_Operation.GetValue("DocEntry", dbds_Operation.Offset).Trim();
                string BaseSerialNum = dbds_Operation.GetValue("U_SerialNum", dbds_Operation.Offset).Trim();

                CurrentForm.DataSources.UserDataSources.Item("BoType").ValueEx = BaseType;
                CurrentForm.DataSources.UserDataSources.Item("BoEntry").ValueEx = BaseEntry;
                CurrentForm.DataSources.UserDataSources.Item("BoSerial").ValueEx = BaseSerialNum;
                CurrentForm.DataSources.UserDataSources.Item("Remarks").ValueEx = dbds_Operation.GetValue("U_ref1", dbds_Operation.Offset).Trim();
                CurrentForm.DataSources.UserDataSources.Item("CardCode").ValueEx = dbds_Operation.GetValue("U_CardCode", dbds_Operation.Offset).Trim();
                CurrentForm.DataSources.UserDataSources.Item("CardName").ValueEx = dbds_Operation.GetValue("U_CardName", dbds_Operation.Offset).Trim();
                CurrentForm.DataSources.UserDataSources.Item("CntctCode").ValueEx = dbds_Operation.GetValue("U_CntctCode", dbds_Operation.Offset).Trim();
                CurrentForm.DataSources.UserDataSources.Item("DocDate").ValueEx = DateTime.Now.ToString("yyyyMMdd");
                /*目的港代理*/
                this.CurrentForm.DataSources.UserDataSources.Item("EdPCode").Value = dbds_Operation.GetValue("U_EndDelegateCode", dbds_Operation.Offset).Trim();
                this.CurrentForm.DataSources.UserDataSources.Item("EdPName").Value = dbds_Operation.GetValue("U_EndDelegateName", dbds_Operation.Offset).Trim();
                LoadFormData();
                #region 计算利润
                SumRMB(CurrentForm);
                DebitSumRMB(CurrentForm);
                CreditSumRMB(CurrentForm);
                #endregion
                SBOApp.StatusBar.SetText("数据项加载完成.", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
            }
            #endregion
            this.CurrentForm.Freeze(false);
        }
        #endregion
        #region 事件处理
        void B1Form_CreateCost_frm_ChooseFormListEvent(SAPBoAddon.B1AddonBase.B1ChooseFormList pVal, ref bool BubbleEvent)
        {
            SAPbouiCOM.Matrix omtx = default(SAPbouiCOM.Matrix);
            SAPbouiCOM.Conditions cons;
            SAPbouiCOM.Condition con;
            SAPbouiCOM.ChooseFromList cfl;
            SAPbobsCOM.Recordset oRst = (SAPbobsCOM.Recordset)SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);


            if (pVal.BeforeAction)
            {
                cfl = this.CurrentForm.ChooseFromLists.Item(pVal.ChooseFromListUID);
                switch (pVal.ChooseFromListUID)
                {
                    #region 结算单位 应收
                    case "CFL_CloseCode":
                    case "CFL_CloseName":
                    case "CFL_CloseNameF":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "CardType";
                        con.CondVal = "C";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "QryGroup14";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_CloseCode2":
                    case "CFL_CloseName2":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "CardType";
                        con.CondVal = "S";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "QryGroup14";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    #endregion
                    #region 费用
                    //应收费用
                    case "CFL_CodeBars":
                    case "CFL_ItemName":
                    //应付费用
                    case "CFL_CodeBars2":
                    case "CFL_ItemName2":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        //除机场操作外，其他的用户不能选择机场现结费用。
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "ItmsGrpCod";
                        con.CondVal = "102";//监管库现结
                        con.Operation = BoConditionOperation.co_NOT_EQUAL;


                        con.Relationship = BoConditionRelationship.cr_AND;
                        string CardName = this.CurrentForm.DataSources.UserDataSources.Item("CardName").ValueEx;
                        if (CardName.IndexOf("西门子") >= 0)
                        {
                            con = cons.Add();
                            con.Alias = "U_ParterGroup";
                            con.CondVal = "O"; //客户组不等于其他-O
                            con.Operation = BoConditionOperation.co_NOT_EQUAL;

                        }
                        else
                        {
                            con = cons.Add();
                            con.Alias = "U_ParterGroup";
                            con.CondVal = "S"; //客户组不等于西门子-S
                            con.Operation = BoConditionOperation.co_NOT_EQUAL;
                        }
                        cfl.SetConditions(cons);
                        break;
                    #endregion
                }

            }
            else
            {
                switch (pVal.ChooseFromListUID)
                {
                    //应收费用
                    case "CFL_CodeBars":
                    case "CFL_ItemName":
                    //应付费用
                    case "CFL_CodeBars2":
                    case "CFL_ItemName2":
                        this.ChooseFeeItemSetValue(pVal);
                        break;
                    //结算单位
                    case "CFL_CloseCode":
                    case "CFL_CloseName":
                    case "CFL_CloseNameF":
                        omtx = (SAPbouiCOM.Matrix)this.CurrentForm.Items.Item("mtx_0").Specific;
                        object LineId = SAPBoAddon.B1Assistant.Matrix.GetCellValue(omtx, "col_f", pVal.Row);
                        SAPbouiCOM.DataTable Dt_Rece = this.CurrentForm.DataSources.DataTables.Item("DT_Rece");
                        omtx.GetLineData(pVal.Row);
                        Dt_Rece.Rows.Offset = this.GetDataTableOffset(Dt_Rece, LineId);

                        Dt_Rece.SetValue("CardCode", Dt_Rece.Rows.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        Dt_Rece.SetValue("CardName", Dt_Rece.Rows.Offset, pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        Dt_Rece.SetValue("Cashier", Dt_Rece.Rows.Offset, pVal.SelectedObjects.GetValue("U_Sale", 0).ToString());//收款负责人
                        omtx.SetLineData(pVal.Row);

                        int BoEntry = Dt_Rece.GetValue("DocEntry", Dt_Rece.Rows.Offset);
                        int LineNum = Dt_Rece.GetValue("LineNum", Dt_Rece.Rows.Offset);
                        this.ItemChanged(BoEntry, LineNum, pVal.SelectedObjects.GetValue("CardCode", 0).ToString(), "CardCode", OrderType.SalesOrder);
                        this.ItemChanged(BoEntry, LineNum, pVal.SelectedObjects.GetValue("U_Sale", 0).ToString(), "Cashier", OrderType.SalesOrder);
                        break;
                    //结算单位
                    case "CFL_CloseCode2":
                    case "CFL_CloseName2":
                    case "CFL_CloseNameF2":
                        omtx = (SAPbouiCOM.Matrix)this.CurrentForm.Items.Item("mtx_1").Specific;
                        LineId = SAPBoAddon.B1Assistant.Matrix.GetCellValue(omtx, "col_f", pVal.Row);
                        SAPbouiCOM.DataTable Dt_Pay = this.CurrentForm.DataSources.DataTables.Item("DT_Pay");
                        omtx.GetLineData(pVal.Row);
                        Dt_Pay.Rows.Offset = this.GetDataTableOffset(Dt_Pay, LineId);

                        Dt_Pay.SetValue("CardCode", Dt_Pay.Rows.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        Dt_Pay.SetValue("CardName", Dt_Pay.Rows.Offset, pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        Dt_Pay.SetValue("Cashier", Dt_Pay.Rows.Offset, pVal.SelectedObjects.GetValue("U_Sale", 0).ToString());//收款负责人
                        omtx.SetLineData(pVal.Row);

                        BoEntry = Dt_Pay.GetValue("DocEntry", Dt_Pay.Rows.Offset);
                        LineNum = Dt_Pay.GetValue("LineNum", Dt_Pay.Rows.Offset);
                        this.ItemChanged(BoEntry, LineNum, pVal.SelectedObjects.GetValue("CardCode", 0).ToString(), "CardCode", OrderType.Purchase);
                        this.ItemChanged(BoEntry, LineNum, pVal.SelectedObjects.GetValue("U_Sale", 0).ToString(), "Cashier", OrderType.Purchase);
                        break;
                }
            }

        }

        void B1Form_CreateCost_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                if (pVal.ItemUID == "1" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_CLICK)
                {
                    if (CurrentFormEx.Mode == SAPbouiCOM.BoFormMode.fm_OK_MODE)
                    {
                        BubbleEvent = true;
                        return;
                    }
                    SBOApp.StatusBar.SetText("正在执行操作,请稍后..", SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Warning);
                    CurrentFormEx.Items.Item("lr3").Specific.Active = true;
                    BoAddonBiz_FreightForwarder.Cost.Bo.CreateOrder oCreateOrder = new CreateOrder();
                    //判断费用有没有录入结算单位
                    if (B1Order.IsCompanyNull())
                    {
                        BubbleEvent = false;
                        SBOApp.MessageBox("结算单位为空，请检查录入的费用。");
                        return;
                    }
                    oCreateOrder.OrderLines = B1Order;
                    oCreateOrder.SBOCompany = SBOCompany;
                    oCreateOrder.ors = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                    try
                    {
                        bool isSuc = oCreateOrder.HanldeOrder();
                        if (isSuc)
                        {
                            SAPbobsCOM.Recordset rs = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                            string Table = this.CurrentForm.DataSources.UserDataSources.Item("BPTable").ValueEx.Trim();
                            string SQL = "UPDATE [" + Table + "] SET U_ref1 = '" + CurrentForm.DataSources.UserDataSources.Item("Remarks").Value + "' Where DocEntry =  " + this.CurrentForm.DataSources.UserDataSources.Item("BoEntry").ValueEx.Trim();
                            rs.DoQuery(SQL);
                        }
                    }
                    catch (Exception ex)
                    {
                        BubbleEvent = false;
                        SBOApp.MessageBox(ex.Message);
                        return;
                    }
                    LoadFormData();
                    SBOApp.StatusBar.SetText("操作成功！", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
                    CurrentForm.Mode = SAPbouiCOM.BoFormMode.fm_OK_MODE;
                    BubbleEvent = false;
                }
            }
            else
            {
                //数据来源（基于）
                if (pVal.ItemUID == "57" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT)
                {
                    BaseTypeComboBox(pVal.FormUID);
                }
                #region 页面数据刷新到对象
                if (pVal.ItemUID == "mtx_0" && pVal.Row > 0 && pVal.ItemChanged && pVal.EventType == SAPbouiCOM.BoEventTypes.et_VALIDATE)
                {
                    this.FlushData(pVal.ItemUID, pVal.ColUID, pVal.Row, OrderType.SalesOrder);
                }
                if (pVal.ItemUID == "mtx_0" && pVal.ColUID == "col_c" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_CLICK)
                {
                    this.FlushData(pVal.ItemUID, pVal.ColUID, pVal.Row, OrderType.SalesOrder);
                    SAPbouiCOM.Matrix oMtx = CurrentFormEx.ItemsEx.ItemEx("mtx_0").Specific;
                    oMtx.GetCellSpecific("col_o15", pVal.Row).Value = DateTime.Now.ToString("yyyy-MM-dd hh:mm");
                    oMtx.GetCellSpecific("col_o16", pVal.Row).Value = Utils.GetUserToEmployee(SBOCompany, SBOCompany.UserSignature).Name;
                    this.FlushData(pVal.ItemUID, "col_o15", pVal.Row, OrderType.SalesOrder);
                    this.FlushData(pVal.ItemUID, "col_o16", pVal.Row, OrderType.SalesOrder);
                }
                if (pVal.ItemUID == "mtx_1" && pVal.ColUID == "col_c" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_CLICK)
                {
                    this.FlushData(pVal.ItemUID, pVal.ColUID, pVal.Row, OrderType.Purchase);
                    SAPbouiCOM.Matrix oMtx = CurrentFormEx.ItemsEx.ItemEx("mtx_1").Specific;
                    oMtx.GetCellSpecific("col_o15", pVal.Row).Value = DateTime.Now.ToString("yyyy-MM-dd hh:mm");
                    oMtx.GetCellSpecific("col_o16", pVal.Row).Value = Utils.GetUserToEmployee(SBOCompany, SBOCompany.UserSignature).Name;
                    this.FlushData(pVal.ItemUID, "col_o15", pVal.Row, OrderType.Purchase);
                    this.FlushData(pVal.ItemUID, "col_o16", pVal.Row, OrderType.Purchase);
                }
                if (pVal.ItemUID == "mtx_0" && pVal.ColUID == "col_19" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT && pVal.Row > 0)
                {
                    this.FlushData(pVal.ItemUID, pVal.ColUID, pVal.Row, OrderType.SalesOrder);
                }
                if (pVal.ItemUID == "mtx_1" && pVal.Row > 0 && (pVal.ItemChanged || pVal.EventType == SAPbouiCOM.BoEventTypes.et_LOST_FOCUS) && pVal.EventType == SAPbouiCOM.BoEventTypes.et_VALIDATE)
                {
                    this.FlushData(pVal.ItemUID, pVal.ColUID, pVal.Row, OrderType.Purchase);
                }
                if (pVal.ItemUID == "mtx_1" && pVal.ColUID == "col_19" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT && pVal.Row > 0)
                {
                    this.FlushData(pVal.ItemUID, pVal.ColUID, pVal.Row, OrderType.Purchase);
                }
                #endregion
                #region 计量单位
                if (pVal.ItemUID == "mtx_0" && pVal.ColUID == "col_Unit" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT && pVal.Row > 0)
                {
                    this.ChangeItemQuantity(pVal.ItemUID, pVal.Row, OrderType.SalesOrder);
                    this.FlushData(pVal.ItemUID, pVal.ColUID, pVal.Row, OrderType.SalesOrder);
                    this.CalculateRMB(pVal.ItemUID, pVal.ColUID, "DT_Rece", pVal.Row, false, true);
                    this.CurrentForm.Items.Item("mtx_0").Specific.SetCellFocus(pVal.Row, 13);//使"单据"列获取焦点
                }
                if (pVal.ItemUID == "mtx_1" && pVal.ColUID == "col_Unit" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT && pVal.Row > 0)
                {
                    this.ChangeItemQuantity(pVal.ItemUID, pVal.Row, OrderType.Purchase);
                    this.FlushData(pVal.ItemUID, pVal.ColUID, pVal.Row, OrderType.Purchase);
                    this.CalculateRMB(pVal.ItemUID, pVal.ColUID, "DT_Pay", pVal.Row, false, true);
                    this.CurrentForm.Items.Item("mtx_1").Specific.SetCellFocus(pVal.Row, 13);//使"单据"列获取焦点
                }
                #endregion
                #region 是否显示增值税
                if (pVal.ItemUID == "mtx_0" && pVal.ColUID == "col_IsTax" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT && pVal.Row > 0)
                {
                    this.FlushData(pVal.ItemUID, pVal.ColUID, pVal.Row, OrderType.SalesOrder);
                }
                //if (pVal.ItemUID == "mtx_1" && pVal.ColUID == "col_IsTax" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT && pVal.Row > 0)
                //{
                //    this.FlushData(pVal.ItemUID, pVal.ColUID, pVal.Row, OrderType.Purchase);
                //}
                #endregion

                #region 计算应付的费用金额
                //计算应收的费用金额
                if (pVal.ItemUID == "mtx_0" && new string[] { "col_20", "col_0VAT", "col_24", "col_tax", "col_22" }.Contains(pVal.ColUID)
                    && pVal.EventType == SAPbouiCOM.BoEventTypes.et_VALIDATE && pVal.ItemChanged)
                {
                    this.CalculateRMB(pVal.ItemUID, pVal.ColUID, "DT_Rece", pVal.Row, false, true);
                }
                if (pVal.ItemUID == "mtx_1" && new string[] { "col_20", "col_24", "col_tax", "col_22" }.Contains(pVal.ColUID)
                    && pVal.EventType == SAPbouiCOM.BoEventTypes.et_VALIDATE && pVal.ItemChanged)
                {
                    this.CalculateRMB(pVal.ItemUID, pVal.ColUID, "DT_Pay", pVal.Row, false, true);
                }
                if (pVal.ItemUID == "mtx_0" && pVal.ColUID == "col_19" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT)
                {
                    this.CalculateRMB(pVal.ItemUID, pVal.ColUID, "DT_Rece", pVal.Row);
                }
                if (pVal.ItemUID == "mtx_1" && pVal.ColUID == "col_19" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT)
                {
                    this.CalculateRMB(pVal.ItemUID, pVal.ColUID, "DT_Pay", pVal.Row);
                }
                //if (pVal.ItemUID == "mtx_0" && pVal.ColUID == "col_22" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_VALIDATE)
                //{
                //    this.CalculateRMB(pVal.ItemUID, pVal.ColUID, "DT_Rece", pVal.Row, false);
                //}
                //if (pVal.ItemUID == "mtx_1" && pVal.ColUID == "col_22" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_VALIDATE)
                //{
                //    this.CalculateRMB(pVal.ItemUID, pVal.ColUID, "DT_Pay", pVal.Row, false);
                //}
                //if (pVal.ItemUID == "mtx_0" && pVal.ColUID == "col_tax" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_VALIDATE)
                //{
                //    this.CalculateRMB(pVal.ItemUID, pVal.ColUID, "DT_Rece", pVal.Row, false);
                //}
                //if (pVal.ItemUID == "mtx_1" && pVal.ColUID == "col_tax" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_VALIDATE)
                //{
                //    this.CalculateRMB(pVal.ItemUID, pVal.ColUID, "DT_Pay", pVal.Row, false);
                //}
                #endregion
                #region 币种的更新
                //选择币种
                if (pVal.ItemUID == "lr3" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT)
                {
                    this.OtherCurrencyProfit();
                }
                //应收选择币种
                if (pVal.ItemUID == "dlr3" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT)
                {
                    this.DebitOtherCurrencyProfit();
                }
                //应付选择币种
                if (pVal.ItemUID == "clr3" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT)
                {
                    this.CreditOtherCurrencyProfit();
                }
                #endregion
                #region 计算金额
                //表格中金额变化
                if (pVal.ItemChanged && ((pVal.ItemUID == "mtx_0" && new string[] { "col_19", "col_20", "col_0VAT", "col_22", "col_21", "col_24", "col_25", "col_tax" }.Contains(pVal.ColUID)) || (pVal.ItemUID == "mtx_1" && new string[] { "col_19", "col_20", "col_22", "col_21", "col_24", "col_25", "col_tax" }.Contains(pVal.ColUID))))
                {
                    SumRMB(CurrentForm, pVal.ItemUID, pVal.Row);
                    DebitSumRMB(CurrentForm, pVal.ItemUID, pVal.Row);
                }
                if ((pVal.ItemUID == "mtx_0" || pVal.ItemUID == "mtx_1") && pVal.EventType == SAPbouiCOM.BoEventTypes.et_LOST_FOCUS)
                {
                    SumRMB(CurrentForm);
                    CreditSumRMB(CurrentForm);
                }
                #endregion
                #region 添加行 删除行
                if (pVal.ItemUID == "67" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    this.AddNewLine(OrderType.SalesOrder, "DT_Rece", "mtx_0");
                }
                if (pVal.ItemUID == "68" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    this.DeleteLine(OrderType.SalesOrder, "DT_Rece", "mtx_0");
                    this.SetFeeMatrixRowDisable("mtx_0");
                }
                if (pVal.ItemUID == "43" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    this.AddNewLine(OrderType.Purchase, "DT_Pay", "mtx_1");
                }
                if (pVal.ItemUID == "44" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    this.DeleteLine(OrderType.Purchase, "DT_Pay", "mtx_1");
                    this.SetFeeMatrixRowDisable("mtx_1");
                }
                #endregion
                #region 审核与取消审核
                //审核
                if (pVal.ItemUID == "CCheck" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    //Check(pVal.FormUID, "mtx_1");
                    CheckFromDataTable(pVal.FormUID, "mtx_1");
                }
                if (pVal.ItemUID == "DCheck" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    //Check(pVal.FormUID, "mtx_0");
                    CheckFromDataTable(pVal.FormUID, "mtx_0");
                }
                //取消审核
                if (pVal.ItemUID == "CCancel" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    ReCheck(pVal.FormUID, "mtx_1");
                }
                if (pVal.ItemUID == "DCancel" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    ReCheck(pVal.FormUID, "mtx_0");
                }
                #endregion
                #region 订单发送
                if ((pVal.ItemUID == "DSend" || pVal.ItemUID == "CSend") && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    this.SendMessage(pVal.ItemUID);
                }
                #endregion
                #region 费用审核、取消审核
                if ((pVal.ItemUID == "DApp" || pVal.ItemUID == "CApp") && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    this.ApprovedFee(pVal.ItemUID);
                }
                if ((pVal.ItemUID == "DAppC" || pVal.ItemUID == "CAppC") && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    this.ApprovedFee_Cancel(pVal.ItemUID);
                }

                #endregion
                #region 不加税点  注释掉 by wangpeng 2014年7月9日11:23:12
                //if (pVal.ItemUID == "btnTax" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                //{
                //    SAPbouiCOM.Matrix mtx = CurrentForm.Items.Item("mtx_0").Specific;
                //    for (int i = 1; i <= mtx.RowCount; i++)
                //    {
                //        if (mtx.CommonSetting.GetCellEditable(i, 9))
                //            SAPBoAddon.B1Assistant.Matrix.SetCellValue(mtx, "col_tax", i, "0.0");
                //    }
                //}
                #endregion
            }
        }

        void B1Form_CreateCost_frm_FormDataEvent(SAPBoAddon.B1AddonBase.B1BusinessObjectInfo pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
            }
            else
            {
                if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_DATA_LOAD)
                {
                    #region 计算利润
                    SumRMB(CurrentForm);
                    DebitSumRMB(CurrentForm);
                    CreditSumRMB(CurrentForm);
                    #endregion
                    this.LoadFormData();
                }
            }
        }
        #endregion
        #region 私有方法
        /// <summary>
        /// 选择审核
        /// </summary>
        /// <param name="FormUID"></param>
        /// <param name="ItemUID"></param>
        private void Check(string FormUID, string ItemUID)
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.Item(FormUID);
            SAPbouiCOM.Matrix oMtx = oForm.Items.Item(ItemUID).Specific;
            SBOApp.SetStatusBarMessage("开始审核……", SAPbouiCOM.BoMessageTime.bmt_Short, false);
            for (int i = 1; i <= oMtx.RowCount; i++)
            {
                SBOApp.SetStatusBarMessage("正在处理 " + oMtx.RowCount.ToString() + " / " + i.ToString(), SAPbouiCOM.BoMessageTime.bmt_Short, false);
                if (oMtx.GetCellSpecific("col_c", i).Checked) continue;
                oMtx.GetCellSpecific("col_c", i).Checked = true;
                oMtx.GetCellSpecific("col_o15", i).Value = DateTime.Now.ToString("yyyy-MM-dd hh:mm");
                oMtx.GetCellSpecific("col_o16", i).Value = Utils.GetUserToEmployee(SBOCompany, SBOCompany.UserSignature).Name;
                OrderType type;
                if (ItemUID == "mtx_0")
                { type = OrderType.SalesOrder; }
                else
                { type = OrderType.Purchase; }
                this.FlushData(ItemUID, "col_c", i, type);
                this.FlushData(ItemUID, "col_o15", i, type);
                this.FlushData(ItemUID, "col_o16", i, type);
            }
            SBOApp.SetStatusBarMessage("审核完成！", SAPbouiCOM.BoMessageTime.bmt_Short, false);
        }

        /// <summary>
        /// 从数据源审核费用项
        /// </summary>
        /// <author>WangPeng</author>
        private void CheckFromDataTable(string FormUID, string ItemUID)
        {
            string TableName = ItemUID == "mtx_0" ? "DT_Rece" : "DT_Pay";
            SAPbouiCOM.Form oForm = SBOApp.Forms.Item(FormUID);
            SAPbouiCOM.Matrix oMtx = oForm.Items.Item(ItemUID).Specific;
            SAPbouiCOM.DataTable DT_Rece = oForm.DataSources.DataTables.Item(TableName);
            SBOApp.SetStatusBarMessage("审核中..", SAPbouiCOM.BoMessageTime.bmt_Short, false);
            oMtx.FlushToDataSource();
            string IsCheck = string.Empty;
            string LineStatus = string.Empty;
            OrderType type = ItemUID == "mtx_0" ? OrderType.SalesOrder : type = OrderType.Purchase;
            for (int i = 0; i < DT_Rece.Rows.Count; i++)
            {
                SBOApp.SetStatusBarMessage(" " + oMtx.RowCount.ToString() + " / " + i.ToString(), SAPbouiCOM.BoMessageTime.bmt_Short, false);
                SBOApp.StatusBar.SetText(string.Format("正在处理{0}/{1}", i + 1, DT_Rece.Rows.Count), SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Warning);
                DT_Rece.Rows.Offset = i;
                IsCheck = DT_Rece.GetValue("IsCheck", i);
                LineStatus = DT_Rece.GetValue("LineStatus", i);
                if ((IsCheck == "N" || string.IsNullOrEmpty(IsCheck)) && LineStatus != "C")
                {
                    DT_Rece.SetValue("IsCheck", i, "Y");
                    DT_Rece.SetValue("CheckDate", i, DateTime.Now.ToString("yyyy-MM-dd hh:mm"));
                    DT_Rece.SetValue("Checker", i, Utils.GetUserToEmployee(SBOCompany, SBOCompany.UserSignature).Name);

                    oMtx.SetLineData(i + 1);/*刷新到Matrix行*/
                    this.FlushData(ItemUID, "col_c", 1 + i, type);
                    this.FlushData(ItemUID, "col_o15", 1 + i, type);
                    this.FlushData(ItemUID, "col_o16", 1 + i, type);
                }
            }
            if (this.CurrentForm.Mode == SAPbouiCOM.BoFormMode.fm_OK_MODE)
            {
                this.CurrentForm.Mode = SAPbouiCOM.BoFormMode.fm_UPDATE_MODE;
            }
            SBOApp.StatusBar.SetText("已审核", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
        }

        private void ReCheck(string FormUID, string ItemUID)
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.Item(FormUID);
            SAPbouiCOM.Matrix oMtx = oForm.Items.Item(ItemUID).Specific;
            int i = oMtx.GetNextSelectedRow();
            if (i <= 0) return;
            SBOApp.SetStatusBarMessage("取消审核……", SAPbouiCOM.BoMessageTime.bmt_Short, false);
            while (i > 0)
            {
                SBOApp.SetStatusBarMessage("正在处理 " + oMtx.RowCount.ToString() + " / " + i.ToString(), SAPbouiCOM.BoMessageTime.bmt_Short, false);
                if (oMtx.GetCellSpecific("col_c", i).Checked)
                {
                    if (oMtx.GetCellSpecific("col_o14", i).Value == "C")
                    {
                        SBOApp.SetStatusBarMessage("第 " + i.ToString() + " 行数据已生成账单或已核销。所以不能取消审核", SAPbouiCOM.BoMessageTime.bmt_Short, false);
                        oMtx.SelectRow(i, false, false);
                        i = oMtx.GetNextSelectedRow();
                        continue;
                    }
                    for (int colIndex = 0; colIndex < oMtx.Columns.Count; colIndex++)
                    {
                        if (oMtx.Columns.Item(colIndex).Editable)
                        {
                            oMtx.CommonSetting.SetCellEditable(i, colIndex, true);
                        }
                    }
                    oMtx.GetCellSpecific("col_c", i).Checked = false;
                    oMtx.GetCellSpecific("col_o15", i).Value = "";
                    oMtx.GetCellSpecific("col_o16", i).Value = "";
                    OrderType type;
                    if (ItemUID == "mtx_0")
                    { type = OrderType.SalesOrder; }
                    else
                    { type = OrderType.Purchase; }
                    this.FlushData(ItemUID, "col_c", i, type);
                    this.FlushData(ItemUID, "col_o15", i, type);
                    this.FlushData(ItemUID, "col_o16", i, type);
                }
                oMtx.SelectRow(i, false, false);
                i = oMtx.GetNextSelectedRow();
            }
            SBOApp.SetStatusBarMessage("完成！", SAPbouiCOM.BoMessageTime.bmt_Short, false);

        }
        /// <summary>
        /// 数据来源（基于）
        /// </summary>
        private void BaseTypeComboBox(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.Form oChildForm;
            SAPbouiCOM.Form oParentForm;
            string BaseType;
            SAPbouiCOM.DataTable dt;
            SAPbouiCOM.Grid oGrid;
            SAPbouiCOM.ComboBox oCmb;
            SAPbobsCOM.Recordset ors;
            string TableName = string.Empty;

            oForm = SBOApp.Forms.Item(FormUID);
            oParentForm = SBOApp.Forms.Item(oForm.DataSources.UserDataSources.Item("ParentUID").Value);
            ors = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            #region 条件
            if (oForm.Mode != SAPbouiCOM.BoFormMode.fm_ADD_MODE && oForm.Mode != SAPbouiCOM.BoFormMode.fm_OK_MODE && oForm.Mode != SAPbouiCOM.BoFormMode.fm_UPDATE_MODE) return; /*增加[确认]、[更新]状态下弹出列表  [2012-2-7 WangPeng]*/
            BaseType = SAPBoAddon.B1Assistant.Item.GetValue(oForm, "57").ToString();
            if (BaseType == "") return;
            #endregion
            oChildForm = SAPBoAddon.B1Assistant.Form.LoadToSBOApplciation(System.Windows.Forms.Application.StartupPath + @"\Form\AVA_FF_CreateCostListForm.srf", "", true);
            #region 设置主了窗体UID
            oForm.DataSources.UserDataSources.Item("ChildUID").Value = oChildForm.UniqueID;
            oChildForm.DataSources.UserDataSources.Item("ParentUID").Value = oForm.UniqueID;
            #endregion

            oGrid = oChildForm.Items.Item("Grid").Specific;
            oGrid.SelectionMode = SAPbouiCOM.BoMatrixSelect.ms_Single;
            dt = oChildForm.DataSources.DataTables.Add("Table");

            string AVA_OQOT = "AVA_FF_OQOT";
            if (oParentForm.TypeEx == B1FormTypes.ado_AVA_SE_BusinessOperation)
            {
                AVA_OQOT = "AVA_SE_OQOT";
            }
            if (oParentForm.TypeEx == B1FormTypes.ado_AVA_LN_BusinessOperation)
            {
                AVA_OQOT = "AVA_LN_OQOT";
            }
            string InOut = this.CurrentForm.DataSources.UserDataSources.Item("InOut").Value.Trim();

            if (BaseType == "S")//费用方案
            {
                oChildForm.Title = oChildForm.Title + "费用方案";
                dt.ExecuteQuery(@"SELECT DocEntry,U_SerialNum,U_DocDate,U_ScenarioCode,U_ScenarioName,U_ref1,U_ref2,U_Remarks
                                FROM [@AVA_FF_OFEE] Where Status = 'O'");
                TableName = "@AVA_FF_OFEE";
                oChildForm.DataSources.UserDataSources.Item("BaseType").Value = "S";
            }
            if (BaseType == "Q")//报价
            {
                oChildForm.Title = oChildForm.Title + "报价";
                string SQL_Query = String.Format(@"SELECT DocEntry,U_SerialNum,U_DocDate,U_Description,U_CardCode,U_CardName,U_ValidDateForm,U_ValidDateTill,U_AcceptDate,U_DocDueDate,U_ref1,U_ref2,U_Remarks
                                FROM [@{0}] 
                                Where U_Status = 'R'", AVA_OQOT); /*想想维护代码的人吧，不差这一个变量的，哥*/
                dt.ExecuteQuery(SQL_Query);
                TableName = "@" + AVA_OQOT;// "@AVA_FF_OQOT";

                oChildForm.DataSources.UserDataSources.Item("BaseType").Value = "Q";
            }

            oChildForm.DataSources.UserDataSources.Item("CardCode").Value = CurrentForm.DataSources.UserDataSources.Item("CardCode").ValueEx.Trim();
            oChildForm.DataSources.UserDataSources.Item("CardName").Value = CurrentForm.DataSources.UserDataSources.Item("CardName").ValueEx.Trim();
            oGrid.DataTable = dt;
            #region 设置列名
            oGrid.Columns.Item(0).TitleObject.Caption = "单据编号";
            ors.DoQuery("SELECT AliasID,Descr FROM [CUFD] Where Sys = 'N' And TableID = '" + TableName + "'");
            if (ors.RecordCount > 0)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    ors.MoveFirst();
                    for (int j = 0; j < ors.RecordCount; j++)
                    {
                        string FieldName = "U_" + ors.Fields.Item("AliasID").Value;
                        if (dt.Columns.Item(i).Name != FieldName)
                        {
                            ors.MoveNext();
                            continue;
                        }
                        oGrid.Columns.Item(i).TitleObject.Caption = ors.Fields.Item("Descr").Value;
                        ors.MoveNext();
                    }

                }
            }
            #endregion
            oChildForm.Items.Item("Grid").Enabled = false;
            oCmb = oChildForm.Items.Item("5").Specific;
            foreach (SAPbouiCOM.GridColumn oGridColumn in oGrid.Columns)
            {
                oCmb.ValidValues.Add(oGridColumn.UniqueID, oGridColumn.TitleObject.Caption);
            }
        }
        /// <summary>
        /// 加载combobox
        /// </summary>
        private void InitializeAllCombobox()
        {
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            Utils.InitialMatrixComboBox(this.SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_19", "CurrCode", "CurrName", "OCRN", null, null, null);//col_19币种
            Utils.InitialMatrixComboBox(this.SBOCompany, this.CurrentForm.Items.Item("mtx_1").Specific, "col_19", "CurrCode", "CurrName", "OCRN", null, null, null);//col_19币种
            /*只加载可选值*/
            Utils.InitialItemComboBox(SBOCompany, this.CurrentForm.Items.Item("lr3"), "CurrCode", "CurrName", "OCRN", null, "RMB");//费用币种
            Utils.InitialItemComboBox(SBOCompany, this.CurrentForm.Items.Item("dlr3"), "CurrCode", "CurrName", "OCRN", null, "RMB");//费用币种
            Utils.InitialItemComboBox(SBOCompany, this.CurrentForm.Items.Item("clr3"), "CurrCode", "CurrName", "OCRN", null, "RMB");//费用币种
        }

        /// <summary>
        /// 计算折合RMB
        /// </summary>
        /// <author>WangPeng</author>
        private void CalculateRMB(string mtx_uid, string colUID, string TableName, int Row, bool SearchRate = true, bool IsChange_QuantityOrPrice = false)
        {
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            SAPbouiCOM.Matrix oMtx = this.CurrentForm.Items.Item(mtx_uid).Specific;
            SAPbouiCOM.DataTable Table = CurrentFormEx.DataSources.DataTables.Item(TableName);
            string str_DocDate = CurrentForm.DataSources.UserDataSources.Item("DocDate").ValueEx.Trim();
            decimal LineRate = 0, LineCost = 0, LinePrice = 0, LineQuantity = 0, LineTaxRate = 0;
            bool isCol0VAT = false;

            Table.Rows.Offset = GetDataTableOffset(Table, SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_f", Row));
            oMtx.GetLineData(Row);
            string currency = Table.GetValue("Currency", Table.Rows.Offset).ToString().Trim();
            /*查询利率*/
            LineRate = Convert.ToDecimal(string.IsNullOrEmpty(Table.GetValue("Rate", Table.Rows.Offset).ToString().Trim()) ? "0" : Table.GetValue("Rate", Table.Rows.Offset).ToString().Trim());
            if (!string.IsNullOrEmpty(Table.GetValue("TaxRate", Table.Rows.Offset).ToString().Trim()))
            {
                LineTaxRate = Convert.ToDecimal(Table.GetValue("TaxRate", Table.Rows.Offset).ToString().Trim());
            }

            if (mtx_uid == "mtx_0" && (colUID == "col_0VAT" || colUID == "col_20"))
            {
                isCol0VAT = colUID == "col_0VAT";
                string BaseField = isCol0VAT ? "Price0VAT" : "Price";
                string ChangeValueField = isCol0VAT ? "Price" : "Price0VAT";
                decimal linePriceOrPrice0VAT = Convert.ToDecimal(Table.GetValue(BaseField, Table.Rows.Offset));
                decimal ChangeVal = 0;
                if (isCol0VAT)
                {
                    ChangeVal = linePriceOrPrice0VAT * 1.06M;
                    Table.SetValue("IsShowTax", Table.Rows.Offset, "Y");
                }
                else
                {
                    ChangeVal = linePriceOrPrice0VAT / 1.06M;
                    Table.SetValue("IsShowTax", Table.Rows.Offset, "N");
                }
                Table.SetValue(ChangeValueField, Table.Rows.Offset, ChangeVal.ToString());


                IsChange_QuantityOrPrice = true;
            }
            /*数量或单价 值是否变化*/
            if (IsChange_QuantityOrPrice)
            {
                LinePrice = Convert.ToDecimal(Table.GetValue("Price", Table.Rows.Offset).ToString().Trim());
                LineQuantity = Convert.ToDecimal(Table.GetValue("Quantity", Table.Rows.Offset).ToString().Trim());
                /*金额*单价*/
                Table.SetValue("CostMoney", Table.Rows.Offset, (LinePrice * LineQuantity * (1 + LineTaxRate)).ToString());
            }
            if (!string.IsNullOrEmpty(Table.GetValue("CostMoney", Table.Rows.Offset).ToString().Trim()))
            {
                LineCost = Convert.ToDecimal(Table.GetValue("CostMoney", Table.Rows.Offset));
            }
            if (!string.IsNullOrEmpty(Table.GetValue("Rate", Table.Rows.Offset).ToString().Trim()))
            {
                LineRate = Convert.ToDecimal(Table.GetValue("Rate", Table.Rows.Offset));
            }
            Table.SetValue("AmountRMB", Table.Rows.Offset, (LineRate * LineCost).ToString());/*行 折算RMB金额*/
            oMtx.SetLineData(Row);

            //mtx_1 不做此处理，否则错误
            if (mtx_uid == "mtx_0" && (colUID == "col_0VAT" || colUID == "col_20"))
            {
                this.FlushData(mtx_uid, "col_IsTax", Row, OrderType.SalesOrder);
                this.FlushData(mtx_uid, isCol0VAT ? "col_20" : "col_0VAT", Row, OrderType.SalesOrder);
            }

        }
        private void ChooseFeeItemSetValue(SAPBoAddon.B1AddonBase.B1ChooseFormList pVal)
        {
            string MatrixUID = "mtx_0";
            string TableName = "DT_Rece";
            OrderType ordertype;
            SAPbouiCOM.Matrix omtx = default(SAPbouiCOM.Matrix);
            SAPbouiCOM.DataTable dt_Use = default(SAPbouiCOM.DataTable);
            SAPbobsCOM.Recordset ors = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string Default_CardCode = string.Empty;
            string Default_CardName = CurrentForm.DataSources.UserDataSources.Item("CardName").ValueEx.Trim();
            string Default_Cashier = string.Empty;
            Default_CardName = Default_CardName.Replace("'", "+''''+");
            ors.DoQuery("SELECT CardCode,U_Sale FROM OCRD Where CardType = 'C' And CardName = N'" + Default_CardName + "'");
            if (ors.RecordCount > 0)
            {
                Default_CardCode = ors.Fields.Item("CardCode").Value;
                Default_Cashier = ors.Fields.Item("U_Sale").Value;
            }
            ordertype = OrderType.SalesOrder;
            object LineId;
            #region 应付
            if (pVal.ChooseFromListUID == "CFL_CodeBars2" || pVal.ChooseFromListUID == "CFL_ItemName2")
            {
                MatrixUID = "mtx_1";
                TableName = "DT_Pay";
                if (BusinessType != "A")
                {
                    Default_CardName = this.CurrentForm.DataSources.UserDataSources.Item("EdPName").Value;
                    if (string.IsNullOrEmpty(Default_CardName))
                    {
                        Default_CardName = CurrentForm.DataSources.UserDataSources.Item("CardName").ValueEx.Trim();
                    }

                    ors.DoQuery(string.Format("SELECT CardCode,U_Sale FROM OCRD Where CardType = 'S' And CardName = N'{0}'", Default_CardName.Replace("'", "''''")));
                    if (ors.RecordCount > 0)
                    {
                        Default_CardCode = ors.Fields.Item("CardCode").Value;
                        Default_Cashier = ors.Fields.Item("U_Sale").Value;
                    }
                    else
                    {
                        Default_CardCode = "";
                        Default_CardName = "";
                        Default_Cashier = "";
                    }
                }
                else
                {
                    Default_CardCode = "";
                    Default_CardName = "";
                    Default_Cashier = "";
                }
                ordertype = OrderType.Purchase;
            }
            #endregion
            const string Format_InputDate = "yyyy-MM-dd HH:mm";
            dt_Use = CurrentForm.DataSources.DataTables.Item(TableName);
            omtx = (SAPbouiCOM.Matrix)this.CurrentForm.Items.Item(MatrixUID).Specific;
            int CurrentRow = pVal.Row;
            if (pVal.SelectedObjects.Rows.Count > 0)
            {
                LineId = SAPBoAddon.B1Assistant.Matrix.GetCellValue(omtx, "col_f", CurrentRow);
                dt_Use.Rows.Offset = this.GetDataTableOffset(dt_Use, LineId);
                omtx.GetLineData(CurrentRow);
                dt_Use.SetValue("ItemCode", dt_Use.Rows.Offset, pVal.SelectedObjects.GetValue("ItemCode", 0).ToString());
                dt_Use.SetValue("ItemName", dt_Use.Rows.Offset, pVal.SelectedObjects.GetValue("ItemName", 0).ToString());
                dt_Use.SetValue("CodeBars", dt_Use.Rows.Offset, pVal.SelectedObjects.GetValue("CodeBars", 0).ToString());
                dt_Use.SetValue("EnterDate", dt_Use.Rows.Offset, DateTime.Now.ToString(Format_InputDate));
                dt_Use.SetValue("Enterman", dt_Use.Rows.Offset, Utils.GetCurrentUser().Operator);
                dt_Use.SetValue("Quantity", dt_Use.Rows.Offset, 1); /*数量默认为1  Added by WangPeng 2012-6-8*/
                /*应收带主表客户信息；应付带业务单的目的港代理*/
                if (!string.IsNullOrEmpty(Default_CardCode))
                {
                    dt_Use.SetValue("CardCode", dt_Use.Rows.Offset, Default_CardCode);
                    dt_Use.SetValue("CardName", dt_Use.Rows.Offset, Default_CardName);
                    dt_Use.SetValue("Cashier", dt_Use.Rows.Offset, Default_Cashier);
                }
                if (pVal.SelectedObjects.GetValue("ItmsGrpCod", 0) == 100) //往来款
                {
                    dt_Use.SetValue("IsShowTax", dt_Use.Rows.Offset, "N");
                }
                omtx.SetLineData(CurrentRow);
                int BoEntry = dt_Use.GetValue("DocEntry", dt_Use.Rows.Offset);/*订单DocEntry*/
                int LineNum = dt_Use.GetValue("LineNum", dt_Use.Rows.Offset);

                this.ItemChanged(BoEntry, LineNum, Default_CardCode, "CardCode", ordertype);
                this.ItemChanged(BoEntry, LineNum, pVal.SelectedObjects.GetValue("CodeBars", 0).ToString(), "CodeBars", ordertype);
                this.ItemChanged(BoEntry, LineNum, pVal.SelectedObjects.GetValue("ItemCode", 0).ToString(), "ItemCode", ordertype);
                this.ItemChanged(BoEntry, LineNum, 1, "Quantity", ordertype);/*妹的，之前忘了，给中间实体赋值了，汗。。。数量默认为1  Added by WangPeng 2012-6-12*/
                this.ItemChanged(BoEntry, LineNum, Default_Cashier, "Cashier", ordertype);//收款负责人
                if (pVal.SelectedObjects.GetValue("ItmsGrpCod", 0) == 100) //往来款
                {
                    this.ItemChanged(BoEntry, LineNum, "N", "IsShowTax", ordertype);
                }

                string BaseType = CurrentForm.DataSources.UserDataSources.Item("BoType").ValueEx.Trim();
                this.ItemChanged(BoEntry, LineNum, BaseType, "BoType", ordertype);
                string BaseEntry = CurrentForm.DataSources.UserDataSources.Item("BoEntry").ValueEx.Trim();
                this.ItemChanged(BoEntry, LineNum, BaseEntry, "BoEntry", ordertype);
                string BaseSerialNum = CurrentForm.DataSources.UserDataSources.Item("BoSerial").ValueEx.Trim();
                this.ItemChanged(BoEntry, LineNum, BaseSerialNum, "BoSerialNum", ordertype);
                this.ItemChanged(BoEntry, LineNum, DateTime.Now.ToString(Format_InputDate), "EnterDate", ordertype);
                this.ItemChanged(BoEntry, LineNum, Utils.GetCurrentUser().Operator, "Enterman", ordertype);
            }
        }

        /// <summary>
        /// 获取CardFName
        /// </summary>
        /// <author>WangPeng</author>
        private string GetCardForeignName(string CardCode)
        {
            string CardForeignName = string.Empty;
            string SQL_SelectFName = string.Format("SELECT CardFName FROM [OCRD] WHERE CardCode=N'{0}' ", CardCode);
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            oRst.DoQuery(SQL_SelectFName);
            if (oRst.RecordCount > 0)
            {
                CardForeignName = oRst.Fields.Item("CardFName").Value;
            }
            return CardForeignName;
        }
        #region 币种的选择
        /// <summary>
        /// 计算其他货币下的利润
        /// </summary>
        private void OtherCurrencyProfit()
        {
            decimal Profit_RMB = 0, ProfitTaxOffset_RMB = 0;

            string Currency = SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "lr3").ToString().Trim();
            string str_ProfitRMB = SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "lr2").ToString().Trim();
            string str_ProfitTaxOffsetRMB = SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "lr5").ToString().Trim();
            string BopEntry = this.CurrentForm.DataSources.UserDataSources.Item("BoEntry").ValueEx.Trim();
            if (!string.IsNullOrEmpty(str_ProfitRMB))
            {
                Profit_RMB = Convert.ToDecimal(str_ProfitRMB);
            }
            ProfitTaxOffset_RMB = string.IsNullOrEmpty(str_ProfitTaxOffsetRMB) ? 0 : Convert.ToDecimal(str_ProfitTaxOffsetRMB);
            decimal Rate = Utils.GetRateByCurrency(Currency, Utils.GetBopATDDate(BopEntry, this.CurrentForm.DataSources.UserDataSources.Item("BoType").ValueEx.Trim()));
            SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "lr4", decimal.Round(Profit_RMB / Rate, 5));
            SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "lr6", decimal.Round(ProfitTaxOffset_RMB / Rate, 5));
        }
        /// <summary>
        /// 应收货币转换
        /// </summary>
        private void DebitOtherCurrencyProfit()
        {
            decimal Profit_RMB = 0;
            string Currency = SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "dlr3").ToString().Trim();
            string str_ProfitRMB = SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "dlr2").ToString().Trim();
            string BopEntry = this.CurrentForm.DataSources.UserDataSources.Item("BoEntry").ValueEx.Trim();
            if (!string.IsNullOrEmpty(str_ProfitRMB))
            {
                Profit_RMB = Convert.ToDecimal(str_ProfitRMB);
            }
            decimal Rate = Utils.GetRateByCurrency(Currency, Utils.GetBopATDDate(BopEntry, this.CurrentForm.DataSources.UserDataSources.Item("BoType").ValueEx.Trim()));
            SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "dlr4", decimal.Round(Profit_RMB / Rate, 5));
            //税额显示
            decimal Tax_RMB = string.IsNullOrEmpty(SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "dlr6").ToString().Trim()) ? 0 :
                Convert.ToDecimal(SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "dlr6").ToString().Trim());
            SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "dlr5", decimal.Round(Tax_RMB / Rate, 5));
        }
        /// <summary>
        /// 应付货币转换
        /// </summary>
        private void CreditOtherCurrencyProfit()
        {
            decimal Profit_RMB = 0;
            string Currency = SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "clr3").ToString().Trim();
            string str_ProfitRMB = SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "clr2").ToString().Trim();
            string BopEntry = this.CurrentForm.DataSources.UserDataSources.Item("BoEntry").ValueEx.Trim();
            if (!string.IsNullOrEmpty(str_ProfitRMB))
            {
                Profit_RMB = Convert.ToDecimal(str_ProfitRMB);
            }
            decimal Rate = Utils.GetRateByCurrency(Currency, Utils.GetBopATDDate(BopEntry, this.CurrentForm.DataSources.UserDataSources.Item("BoType").ValueEx.Trim()));
            SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "clr4", decimal.Round(Profit_RMB / Rate, 5));
            //税额显示
            decimal Tax_RMB = string.IsNullOrEmpty(SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "clr6").ToString().Trim()) ? 0 :
                Convert.ToDecimal(SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "clr6").ToString().Trim());
            SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "clr5", decimal.Round(Tax_RMB / Rate, 5));
        }
        #endregion
        #region 合计
        /// <summary>
        /// 合计利润
        /// </summary>
        public static void SumRMB(SAPbouiCOM.Form oForm, string ItemUID = null, int row = default(int))
        {
            SAPbouiCOM.DataTable CCT1 = oForm.DataSources.DataTables.Item("DT_Rece");
            SAPbouiCOM.DataTable CCT2 = oForm.DataSources.DataTables.Item("DT_Pay");
            if (string.IsNullOrEmpty(ItemUID) != true)
            {
                /*刷新当前Matrix*/
                SAPbouiCOM.Matrix Mtx_Current = oForm.Items.Item(ItemUID).Specific;
            }
            decimal Total_Receive = 0;/*应收*/
            decimal Total_Pay = 0;
            decimal Total_Porfit = 0, Total_Tax_in = 0, Total_Tax_out = 0;
            decimal LineTemp = 0, lineTaxRate = 0;
            for (int i = 0; i < CCT1.Rows.Count; i++)
            {
                LineTemp = Convert.ToDecimal(CCT1.GetValue("AmountRMB", i));
                lineTaxRate = Convert.ToDecimal(CCT1.GetValue("TaxRate", i).ToString("0.0000").Substring(0, 4));//0.0683 取 0.06
                Total_Tax_in += LineTemp / (1 + lineTaxRate) * lineTaxRate;
                Total_Receive += LineTemp;
                LineTemp = lineTaxRate = 0;
            }

            for (int i = 0; i < CCT2.Rows.Count; i++)
            {
                LineTemp = Convert.ToDecimal(CCT2.GetValue("AmountRMB", i));
                lineTaxRate = Convert.ToDecimal(CCT2.GetValue("TaxRate", i).ToString("0.0000").Substring(0, 4));
                Total_Pay += LineTemp;
                Total_Tax_out += LineTemp / (1 + lineTaxRate) * lineTaxRate;
                LineTemp = lineTaxRate = 0;
            }

            Total_Porfit = Total_Receive - Total_Pay;
            /*应收、应付、利润*/
            SAPBoAddon.B1Assistant.Item.SetValue(oForm, "lr2", Total_Porfit);
            SAPBoAddon.B1Assistant.Item.SetValue(oForm, "lr4", Total_Porfit);
            /*扣税后利润  add by WangPeng 2014年6月17日15:43:50*/
            string Branch = oForm.DataSources.UserDataSources.Item("BoSerial").ValueEx.Trim().Substring(2, 2);
            //（含税收入-含税成本）-（销项税+进项税）-（销项税-进项税）*12% ;（上海地区*13%）
            decimal rate_temp = Branch == "SH" ? 0.13M : 0.12M;
            decimal OperationPorfit = Total_Porfit - (Total_Tax_in - Total_Tax_out) - (Total_Tax_in - Total_Tax_out) * rate_temp;
            if (Branch == "GZ")//-(销售收入-销项税)*0.05%
            {
                OperationPorfit = OperationPorfit - (Total_Receive - Total_Tax_in) * 0.0005M;
            }
            SAPBoAddon.B1Assistant.Item.SetValue(oForm, "lr5", decimal.Round(OperationPorfit, 2));
            SAPBoAddon.B1Assistant.Item.SetValue(oForm, "lr6", decimal.Round(OperationPorfit, 2));
        }
        /// <summary>
        /// 应收合计利润
        /// </summary>
        public static void DebitSumRMB(SAPbouiCOM.Form oForm, string ItemUID = null, int row = default(int))
        {
            SAPbouiCOM.DataTable CCT1 = oForm.DataSources.DataTables.Item("DT_Rece");
            if (string.IsNullOrEmpty(ItemUID) != true)
            {
                /*刷新当前Matrix*/
                SAPbouiCOM.Matrix Mtx_Current = oForm.Items.Item(ItemUID).Specific;
            }
            decimal Total_Receive = 0;/*应收*/
            decimal LineTemp = 0;
            decimal LineTax = 0, Total_Tax = 0;
            string Str_LineTaxRate = "0";
            for (int i = 0; i < CCT1.Rows.Count; i++)
            {
                LineTemp = decimal.Round(Convert.ToDecimal(CCT1.GetValue("AmountRMB", i)), 2);

                Str_LineTaxRate = CCT1.GetValue("TaxRate", i).ToString("0.0000").Substring(0, 4);  // 0.0683 取值 0.06
                LineTax = LineTemp / (1 + Convert.ToDecimal(Str_LineTaxRate)) * Convert.ToDecimal(Str_LineTaxRate);
                Total_Tax += LineTax;
                Total_Receive += LineTemp;
                LineTemp = 0;
            }
            /*应收、应付、利润*/
            SAPBoAddon.B1Assistant.Item.SetValue(oForm, "dlr2", Total_Receive);
            SAPBoAddon.B1Assistant.Item.SetValue(oForm, "dlr4", Total_Receive);
            SAPBoAddon.B1Assistant.Item.SetValue(oForm, "dlr5", decimal.Round(Total_Tax, 2));
            SAPBoAddon.B1Assistant.Item.SetValue(oForm, "dlr6", decimal.Round(Total_Tax, 2));
        }
        /// <summary>
        /// 应付合计利润
        /// </summary>
        public static void CreditSumRMB(SAPbouiCOM.Form oForm, string ItemUID = null, int row = default(int))
        {
            SAPbouiCOM.DataTable CCT2 = oForm.DataSources.DataTables.Item("DT_Pay");
            if (string.IsNullOrEmpty(ItemUID) != true)
            {
                /*刷新当前Matrix*/
                SAPbouiCOM.Matrix Mtx_Current = oForm.Items.Item(ItemUID).Specific;
            }
            decimal Total_Pay = 0;
            decimal LineTemp = 0;
            decimal LineTax = 0, Total_Tax = 0;
            string Str_LineTaxRate = "0";
            for (int i = 0; i < CCT2.Rows.Count; i++)
            {
                LineTemp = decimal.Round(Convert.ToDecimal(CCT2.GetValue("AmountRMB", i)), 2);

                Str_LineTaxRate = CCT2.GetValue("TaxRate", i).ToString();
                LineTax = LineTemp / (1 + Convert.ToDecimal(Str_LineTaxRate)) * Convert.ToDecimal(Str_LineTaxRate);
                Total_Tax += LineTax;
                Total_Pay += LineTemp;
                LineTemp = 0;
            }
            /*应收、应付、利润*/
            SAPBoAddon.B1Assistant.Item.SetValue(oForm, "clr2", Total_Pay);
            SAPBoAddon.B1Assistant.Item.SetValue(oForm, "clr4", Total_Pay);
            SAPBoAddon.B1Assistant.Item.SetValue(oForm, "clr5", decimal.Round(Total_Tax, 2));
            SAPBoAddon.B1Assistant.Item.SetValue(oForm, "clr6", decimal.Round(Total_Tax, 2));
        }
        #endregion
        #region 处理order类
        /// <summary>
        /// Matrix绑定DataTable
        /// </summary>
        private void MatrixColumns_DataBind(string MatrixUID)
        {
            SAPbouiCOM.Matrix oMtx = this.CurrentForm.Items.Item(MatrixUID).Specific;
            string colUID = string.Empty;
            string TableName = string.Empty;
            string FieldName = string.Empty;
            string Xpath_Matrix = string.Format("//item[@uid='{0}']", MatrixUID);
            string Xpath_Columns = "./specific/columns/action/column";
            XmlNode Item_Matrix = this.FormSetting.FormXmlDocument.SelectSingleNode(Xpath_Matrix);
            XmlNodeList xmlNode_Columns = Item_Matrix.SelectNodes(Xpath_Columns);
            XmlNode xmlNode_Table;
            foreach (XmlNode node_Column in xmlNode_Columns)
            {
                colUID = node_Column.Attributes["uid"].Value;
                xmlNode_Table = node_Column.SelectSingleNode("./databind/DataTable");
                if (xmlNode_Table != null)
                {
                    TableName = xmlNode_Table.Attributes["UniqueId"].Value;
                    FieldName = xmlNode_Table.Attributes["ColumnUID"].Value;
                    oMtx.Columns.Item(colUID).DataBind.Bind(TableName, FieldName);

                    if (!Dic_ColField.ContainsKey(colUID))
                    {
                        Dic_ColField.Add(colUID, FieldName);
                    }
                }
                xmlNode_Table = null;
            }
        }
        private void LoadFormData()
        {
            B1Order.Clear();
            SAPbouiCOM.DataTable dt_Rece = this.CurrentForm.DataSources.DataTables.Item("DT_Rece");
            string SQL = string.Empty;
            SQL = "Exec AVA_GetFeeLists  N'{0}',{1},'{2}','{3}'";
            string BaseType = CurrentForm.DataSources.UserDataSources.Item("BoType").ValueEx.Trim();
            string BaseEntry = CurrentForm.DataSources.UserDataSources.Item("BoEntry").ValueEx.Trim();
            string BaseSerialNum = CurrentForm.DataSources.UserDataSources.Item("BoSerial").ValueEx.Trim();
            dt_Rece.ExecuteQuery(string.Format(SQL, BaseType, BaseEntry, BaseSerialNum, "S"));
            if (!string.IsNullOrEmpty(dt_Rece.GetValue("CardCode", 0).Trim()))
            {
                B1Order.LoadBoOrders(dt_Rece, OrderType.SalesOrder);
            }
            SAPbouiCOM.Matrix mtx = CurrentFormEx.Items.Item("mtx_0").Specific;
            mtx.Clear();
            mtx.LoadFromDataSourceEx();
            Utils.SetMatrixRowEnable(SBOApp.Forms.ActiveForm, "mtx_0");
            this.SetFeeMatrixRowDisable("mtx_0");

            SAPbouiCOM.DataTable dt_Pay = this.CurrentFormEx.DataSources.DataTables.Item("DT_Pay");
            SQL = string.Format(SQL, BaseType, BaseEntry, BaseSerialNum, "P");
            dt_Pay.ExecuteQuery(SQL);
            if (!string.IsNullOrEmpty(dt_Pay.GetValue("CardCode", 0).Trim()))
            {
                B1Order.LoadBoOrders(dt_Pay, OrderType.Purchase);
            }
            mtx = CurrentFormEx.Items.Item("mtx_1").Specific;
            mtx.Clear();
            mtx.LoadFromDataSourceEx();
            Utils.SetMatrixRowEnable(SBOApp.Forms.ActiveForm, "mtx_1");
            this.SetFeeMatrixRowDisable("mtx_1");
        }
        /// <summary>
        /// 刷新更改到中间实体
        /// </summary>
        /// <author>WangPeng</author>
        private void FlushData(string MatrixUID, string ColUID, int Row, OrderType ordertype)
        {
            SAPbouiCOM.Matrix oMtx = this.CurrentForm.Items.Item(MatrixUID).Specific;
            int LineNum = Convert.ToInt32(SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_l", Row));
            int B1OrderEntry = Convert.ToInt32(SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_0", Row).ToString());
            object ColValue = SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, ColUID, Row);
            string BopEntry = this.CurrentForm.DataSources.UserDataSources.Item("BoEntry").ValueEx.Trim();

            SAPbouiCOM.DataBind odb = oMtx.Columns.Item(ColUID).DataBind;
            //string FieldName=oMtx.Columns.Item(ColUID).DataBind.Alias;
            if (Dic_ColField[ColUID] == "PaPayDate")
            {
                this.ItemChanged(B1OrderEntry, LineNum, SAPBoAddon.B1Assistant.Time.GetDateTime(ColValue.ToString(), ""), "PaPayDate", ordertype);
            }
            else
            {
                this.ItemChanged(B1OrderEntry, LineNum, ColValue, Dic_ColField[ColUID], ordertype);
            }

            if (Dic_ColField[ColUID] == "Currency")
            {
                if (!string.IsNullOrEmpty(BopEntry))
                {
                    decimal Rate = Utils.GetRateByCurrency(ColValue.ToString(), Utils.GetBopATDDate(BopEntry, this.CurrentForm.DataSources.UserDataSources.Item("BoType").ValueEx.Trim()));
                    SAPBoAddon.B1Assistant.Matrix.SetCellValue(oMtx, "col_22", Row, Rate);
                    oMtx.SetCellFocus(Row, 12);//使"单位"列获取焦点
                    this.ItemChanged(B1OrderEntry, LineNum, Rate, "Rate", ordertype);
                }
            }
        }

        /// <summary>
        /// Matrix 单元格值变化更新实体
        /// </summary>
        public void ItemChanged(int BoDocEntry, int LineNum, object Value, string FieldName, OrderType ordertype)
        {
            OrderLine OrderLine_Changed = B1Order.GetNewOrderLine(BoDocEntry, LineNum, ordertype);
            if (OrderLine_Changed == null)
            {
                OrderLine_Changed = B1Order.GetOrderLine(BoDocEntry, LineNum, ordertype);
            }
            System.Reflection.PropertyInfo oPropertyInfo = null;
            oPropertyInfo = typeof(OrderLine).GetProperty(FieldName);
            if (oPropertyInfo.PropertyType == typeof(string))
            {
                oPropertyInfo.SetValue(OrderLine_Changed, Value.ToString(), null);//类型“System.Decimal”的对象无法转换为类型“System.String”。
            }
            else if (oPropertyInfo.PropertyType == typeof(int) || oPropertyInfo.PropertyType == typeof(Int32))
            {
                oPropertyInfo.SetValue(OrderLine_Changed, Convert.ToInt32(Value), null);
            }
            else if (oPropertyInfo.PropertyType == typeof(DateTime) || oPropertyInfo.PropertyType == typeof(DateTime?))
            {
                oPropertyInfo.SetValue(OrderLine_Changed, Convert.ToDateTime(Value), null);
            }
            else if (oPropertyInfo.PropertyType == typeof(decimal) || oPropertyInfo.PropertyType == typeof(Decimal))
            {
                oPropertyInfo.SetValue(OrderLine_Changed, Convert.ToDecimal(Value), null);
            }
            else if (oPropertyInfo.PropertyType == typeof(double) || oPropertyInfo.PropertyType == typeof(Double))
            {
                oPropertyInfo.SetValue(OrderLine_Changed, Convert.ToDouble(Value), null);
            }
            else
            {
                oPropertyInfo.SetValue(OrderLine_Changed, Value, null);
            }
        }
        private int GetDataTableOffset(SAPbouiCOM.DataTable dt_Use, object LineId)
        {
            int offset_Dt = 0;
            for (int i = 0; i < dt_Use.Rows.Count; i++)
            {
                if (dt_Use.GetValue("Index", i).ToString() == LineId.ToString())
                {
                    offset_Dt = i;
                }
            }
            return offset_Dt;
        }
        private void AddNewLine(OrderType ordertyp, string Table, string MatrixUID, bool isFirst = false)
        {
            SAPbouiCOM.DataTable dt_Rece = this.CurrentForm.DataSources.DataTables.Item(Table);
            SAPbouiCOM.Matrix oMtx = this.CurrentForm.Items.Item(MatrixUID).Specific;

            OrderLine NewOrderLine = B1Order.Add(ordertyp);
            int LineId = 0;
            if (oMtx.RowCount > 0)
            {
                LineId = dt_Rece.GetValue("Index", dt_Rece.Rows.Count - 1);
                dt_Rece.Rows.Add();
            }
            if (dt_Rece.Rows.Count <= 0)
                dt_Rece.Rows.Add();

            dt_Rece.Rows.Offset = dt_Rece.Rows.Count - 1;
            dt_Rece.SetValue("Index", dt_Rece.Rows.Offset, LineId + 1);
            dt_Rece.SetValue("LineNum", dt_Rece.Rows.Offset, NewOrderLine.LineNum);
            dt_Rece.SetValue("DocEntry", dt_Rece.Rows.Offset, NewOrderLine.DocEntry);
            //税点
            if (MatrixUID == "mtx_0")
            {
                NewOrderLine.TaxRate = 0.00;
                dt_Rece.SetValue("TaxRate", dt_Rece.Rows.Offset, NewOrderLine.TaxRate.ToString());
                //added by WangPegn 2014年7月11日15:24:25
                NewOrderLine.IsShowTax = "Y";
                dt_Rece.SetValue("IsShowTax", dt_Rece.Rows.Offset, NewOrderLine.IsShowTax);
            }
            oMtx.AddRow();
            oMtx.SetLineData(oMtx.RowCount);
        }
        private void DeleteLine(OrderType ordertyp, string Table, string MatrixUID)
        {
            SAPbouiCOM.DataTable dt_Rece = this.CurrentForm.DataSources.DataTables.Item(Table);
            SAPbouiCOM.Matrix oMtx = this.CurrentForm.Items.Item(MatrixUID).Specific;
            int SelectRow = 0;
            int DocEntry, LineNum, Index, dtSctRow;
            string IsCheck = string.Empty;
            bool Flag = false;
            oMtx.FlushToDataSource();
            SelectRow = oMtx.GetNextSelectedRow(0, SAPbouiCOM.BoOrderType.ot_RowOrder);
            while (SelectRow > 0)
            {
                int.TryParse(SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_0", SelectRow).ToString().Trim(), out DocEntry);
                int.TryParse(SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_f", SelectRow).ToString().Trim(), out Index);
                LineNum = Convert.ToInt32(SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_l", SelectRow));
                IsCheck = SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_c", SelectRow).ToString().Trim();
                if (IsCheck == "Y")
                {
                    SBOApp.StatusBar.SetText(string.Format("行 [{0}]已审核，不允许删除操作.", Index), SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
                    SelectRow = oMtx.GetNextSelectedRow(SelectRow, SAPbouiCOM.BoOrderType.ot_RowOrder);
                    continue;
                }
                oMtx.DeleteRow(SelectRow);
                dtSctRow = this.GetDataTableOffset(dt_Rece, Index);
                dt_Rece.Rows.Remove(dtSctRow);
                B1Order.Remove(DocEntry, LineNum, ordertyp);
                SelectRow = oMtx.GetNextSelectedRow(0, SAPbouiCOM.BoOrderType.ot_RowOrder);
                Flag = true;
            }
            oMtx.LoadFromDataSourceEx();
            if (CurrentForm.Mode == SAPbouiCOM.BoFormMode.fm_OK_MODE && Flag) CurrentForm.Mode = SAPbouiCOM.BoFormMode.fm_UPDATE_MODE;
        }
        #endregion

        /// <summary>
        /// 计量单位变化刷新数量
        /// </summary>
        /// <author>WangPeng</author>
        private void ChangeItemQuantity(string ItemUID, int Row, OrderType orderType)
        {
            SAPbouiCOM.Matrix oMtx = this.CurrentForm.Items.Item(ItemUID).Specific;
            string ItemCode = SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_12", Row).ToString().Trim();
            string Unit = SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_Unit", Row).ToString().Trim();
            int B1OrderEntry = Convert.ToInt32(SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_0", Row).ToString());
            int LineNum = Convert.ToInt32(SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_l", Row).ToString().Trim());
            string Table_BP = this.CurrentForm.DataSources.UserDataSources.Item("BPTable").ValueEx;

            SAPbouiCOM.Form Form_BusinessOperation = SBOApp.Forms.Item(FormUID_BusinessOperation);
            SAPbouiCOM.DBDataSource dbds = default(SAPbouiCOM.DBDataSource);
            double Quantity = 0d;
            dbds = Form_BusinessOperation.DataSources.DBDataSources.Item(Table_BP);
            Quantity = Convert.ToDouble(dbds.GetValue("U_BillingWeight", dbds.Offset).Trim());/*获取业务单总计费重*/
            if (Unit == "Shipment")/*一票货*/
            {
                Quantity = 1;
            }
            else if (Dic_BoxTypeQty.ContainsKey(Unit))
            {
                Quantity = Dic_BoxTypeQty[Unit];
            }
            Quantity = Quantity > 0 ? Quantity : 1;
            SAPBoAddon.B1Assistant.Matrix.SetCellValue(oMtx, "col_24", Row, Quantity);
            this.ItemChanged(B1OrderEntry, LineNum, Quantity, "Quantity", orderType);
        }

        /// <summary>
        /// 取箱型填充到计量单位
        /// </summary>
        /// <author>WangPeng</author>
        private void GetSEBusinessOperationFCL(string BoEntry)
        {
            SAPbouiCOM.Matrix oMtx = this.CurrentForm.Items.Item("mtx_0").Specific;
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string SQL_GetBoxType = string.Format("SELECT U_BoxType FROM [@AVA_SE_BNO6]  WHERE DocEntry={0}  AND  ISNULL(U_BoxType,N'')<>N''  ", BoEntry);
            oRst.DoQuery(SQL_GetBoxType);
            string BoxType = string.Empty;
            while (!oRst.EoF)
            {
                BoxType = oRst.Fields.Item("U_BoxType").Value.ToString();
                bool flag = false;
                foreach (SAPbouiCOM.ValidValue item in oMtx.Columns.Item("col_Unit").ValidValues)
                {
                    if (item.Value == BoxType)
                        flag = true;
                }
                if (flag == false)
                    oMtx.Columns.Item("col_Unit").ValidValues.Add(BoxType, BoxType);
                if (Dic_BoxTypeQty.ContainsKey(BoxType))
                {
                    Dic_BoxTypeQty[BoxType] = Dic_BoxTypeQty[BoxType] + 1;
                }
                else
                {
                    Dic_BoxTypeQty.Add(BoxType, 1);
                }
                if (!oRst.EoF)
                {
                    oRst.MoveNext();
                }
            }

        }

        /// <summary>
        /// 设置费用表格行不可编辑
        /// </summary>
        /// <author>WangPeng</author>
        private void SetFeeMatrixRowDisable(string MtxUID)
        {
            SAPbouiCOM.Matrix oMtx = this.CurrentForm.Items.Item(MtxUID).Specific;
            string IsCheck = string.Empty;
            string Status = string.Empty;
            for (int i = 1; i <= oMtx.RowCount; i++)
            {
                IsCheck = SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_c", i).ToString();
                Status = SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_o13", i).ToString();
                if (IsCheck == "Y" || Status == "C" || Status == "F" || Status == "D" || Status == "I")
                {
                    oMtx.CommonSetting.SetRowEditable(i, false);
                }
            }
        }

        /// <summary>
        /// 发送费用中的订单到客服
        /// </summary>
        private void SendMessage(string ItemUID)
        {
            SAPbouiCOM.Form oForm = CurrentForm;
            #region 加载需要的审核的数据
            string Table_BP = oForm.DataSources.UserDataSources.Item("BPTable").ValueEx;/*业务单操作 DBDS TableName*/
            SAPbouiCOM.DataTable Dt_Fee = ItemUID == "DSend" ? oForm.DataSources.DataTables.Item("DT_Rece") : oForm.DataSources.DataTables.Item("DT_Pay");
            int DocEntry_Order = 0;
            List<int> List_Order = new List<int>();
            for (int Row = 0; Row < Dt_Fee.Rows.Count; Row++)
            {
                if (Dt_Fee.GetValue("LineStatus", Row) == "O") /*费用行状态为"未清"*/
                {
                    DocEntry_Order = Dt_Fee.GetValue("DocEntry", Row);
                    if (!List_Order.Contains(DocEntry_Order))
                    {
                        List_Order.Add(DocEntry_Order);
                    }
                }
            }
            if (List_Order.Count == 0)
            {
                SBOApp.StatusBar.SetText("暂无需要审核的费用项...", SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Warning);
                return;
            }
            #endregion

            #region 显示选择用户窗体
            String SQL = string.Empty;
            SQL = string.Format(@"SELECT T3.USERID,T1.empId,T4.USER_CODE,T1.Firstname + T1.LastName ChnName,T1.JobTitle EngName FROM OHEM T0
                                                    INNER JOIN OHEM T1 ON T0.Dept = T1.Dept
                                                    INNER JOIN OHPS T2 ON T1.Position = T2.PosID 
                                                    INNER JOIN OUSR T3 ON T0.UserID = T3.UserID
                                                    INNER JOIN OUSR T4 ON T1.UserID = T4.UserID
                                                Where T2.Name = '客服' And T3.UserID = {0}", SBOCompany.UserSignature);
            string ParentUID = SBOApp.Forms.ActiveForm.UniqueID;
            SAPBoAddon.B1FormInitializePar initPar = new SAPBoAddon.B1FormInitializePar();
            initPar.CallType = SAPBoAddon.B1FormCallType.ct_FormItemCall;
            initPar.FatherFormUID = ParentUID;
            initPar.KeyValue = "FeeApparel;" + ItemUID;
            initPar.parObject = SQL;
            this.ShowForm(B1FormTypes.ado_AVA_FF_Message, initPar);
            #endregion
        }

        /// <summary>
        /// 审核应收应付费用
        /// </summary>
        private void ApprovedFee(string ItemUID)
        {
            string Field_UPD = string.Empty, Field_Check = string.Empty, Msg_ReceorPay = string.Empty;
            string Table_BP = this.CurrentForm.DataSources.UserDataSources.Item("BPTable").ValueEx;
            SAPbouiCOM.Form oForm_BP = SBOApp.Forms.Item(this.CurrentForm.DataSources.UserDataSources.Item("ParentUID").Value);
            SAPbouiCOM.DBDataSource dbds_OBNO = oForm_BP.DataSources.DBDataSources.Item(Table_BP);
            string[] ItemGroup_Disable;
            string Status_Approved = "R";//业务单[已批准]状态
            if (ItemUID == "DApp")
            {
                Field_UPD = "U_ReceApproved";
                Field_Check = "U_PayApproved";
                Msg_ReceorPay = "应收";
                ItemGroup_Disable = ItemGroups_Rece;
            }
            else
            {
                Field_UPD = "U_PayApproved";
                Field_Check = "U_ReceApproved";
                Msg_ReceorPay = "应付";
                ItemGroup_Disable = ItemGroups_Pay;
            }
            string BoEntry = this.CurrentForm.DataSources.UserDataSources.Item("BoEntry").ValueEx;
            string BoSerialNum = this.CurrentForm.DataSources.UserDataSources.Item("BoSerial").ValueEx;
            string SQL_UpdateStatus = string.Format(@"UPDATE [{1}] SET {2}=N'Y' WHERE DocEntry={0} 
                    IF EXISTS(SELECT 1 FROM [{1}] WHERE DocEntry={0} AND {3}=N'Y'  AND  U_Status=N'A')
                    UPDATE [{1}] SET U_Status=N'{4}' WHERE DocEntry={0}  AND  U_Status=N'A' ", BoEntry, Table_BP, Field_UPD, Field_Check, Status_Approved);
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            if (SBOApp.MessageBox(string.Format("批准后[{0}费用]不可编辑，是否确定审核？", Msg_ReceorPay), 2, "确定", "取消") == 1)
            {
                oRst.DoQuery(SQL_UpdateStatus);
                SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, ItemGroup_Disable, false);
                dbds_OBNO.SetValue(Field_UPD, dbds_OBNO.Offset, "Y");
                if (dbds_OBNO.GetValue(Field_Check, dbds_OBNO.Offset).Trim() == "Y")
                {
                    Utils.FindForm(oForm_BP, BoEntry);
                }
            }
        }

        /// <summary>
        /// 取消审核
        /// </summary>
        private void ApprovedFee_Cancel(string ItemUID)
        {
            string Field_UPD = string.Empty, Field_Check = string.Empty;
            string Table_BP = this.CurrentForm.DataSources.UserDataSources.Item("BPTable").ValueEx;
            SAPbouiCOM.Form oForm_BP = SBOApp.Forms.Item(this.CurrentForm.DataSources.UserDataSources.Item("ParentUID").Value);
            SAPbouiCOM.DBDataSource dbds_OBNO = oForm_BP.DataSources.DBDataSources.Item(Table_BP);
            string[] ItemGroup_Disable;
            string Status_Operate = "A";//业务单[正操作]状态
            if (ItemUID == "DAppC")
            {
                Field_UPD = "U_ReceApproved";
                Field_Check = "U_PayApproved";
                ItemGroup_Disable = ItemGroups_Rece;
            }
            else
            {
                Field_UPD = "U_PayApproved";
                Field_Check = "U_ReceApproved";
                ItemGroup_Disable = ItemGroups_Pay;
            }
            if (dbds_OBNO.GetValue(Field_UPD, dbds_OBNO.Offset).Trim() == "N")
            {
                SBOApp.StatusBar.SetText("未执行审核操作，取消审核失败.", SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
                return;
            }
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string BoEntry = this.CurrentForm.DataSources.UserDataSources.Item("BoEntry").ValueEx;
            string BoSerialNum = this.CurrentForm.DataSources.UserDataSources.Item("BoSerial").ValueEx;
            oRst.DoQuery(string.Format(" SELECT 1 FROM [{0}] WHERE DocEntry={1} AND U_Status IN (N'P',N'A',N'R') ", Table_BP, BoEntry));
            if (oRst.RecordCount < 1)
            {
                throw new Exception("业务单已结算或已作废，不可取消费用审核");
            }
            string SQL_UpdateStatus = string.Format(@"UPDATE [{1}] SET {2}=N'N' WHERE DocEntry={0} 
                    IF EXISTS(SELECT 1 FROM [{1}] WHERE DocEntry={0} AND {3}=N'N'  AND  U_Status=N'R')
                    UPDATE [{1}] SET U_Status=N'{4}' WHERE DocEntry={0} AND  U_Status=N'R' ", BoEntry, Table_BP, Field_UPD, Field_Check, Status_Operate);

            oRst.DoQuery(SQL_UpdateStatus);
            SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, ItemGroup_Disable, true);
            SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, "1", true);
            dbds_OBNO.SetValue(Field_UPD, dbds_OBNO.Offset, "N");
            if (dbds_OBNO.GetValue(Field_Check, dbds_OBNO.Offset).Trim() == "N" && dbds_OBNO.GetValue("U_Status", dbds_OBNO.Offset).Trim() == "R")
            {
                Utils.FindForm(oForm_BP, BoEntry);
            }
            SBOApp.StatusBar.SetText("取消审核完成.", SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
        }
        /// <summary>
        /// 获取业务类型
        /// </summary>
        /// <param name="ObjectCode"></param>
        /// <returns></returns>
        private string GetBoType(string ObjectCode)
        {
            #region 业务单类型简码(用于存入数据库)
            /// <summary>
            /// 空运业务单
            /// </summary>
            const string BPType_Air = "A";
            /// <summary>
            /// 海运业务单
            /// </summary>
            const string BPType_Sea = "S";
            /// <summary>
            /// 陆运业务单
            /// </summary>
            const string BPType_Land = "L";
            /// <summary>
            /// 其他业务单
            /// </summary>
            const string BPType_Other = "O";
            #endregion
            #region 基本类型
            string BoType = string.Empty;
            //空运
            if (ObjectCode.StartsWith(B1FormTypes.ado_AVA_FF_BusinessOperation))
                BoType = BPType_Air;
            //海运
            if (ObjectCode.StartsWith(B1FormTypes.ado_AVA_SE_BusinessOperation))
                BoType = BPType_Sea;
            //陆运
            if (ObjectCode.StartsWith(B1FormTypes.ado_AVA_LN_BusinessOperation))
                BoType = BPType_Land;
            //其他
            if (ObjectCode.StartsWith(B1FormTypes.ado_AVA_OR_BusinessOperation))
                BoType = BPType_Other;
            #endregion
            return BoType;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="oParentForm"></param>
        /// <param name="ordertyp"></param>
        /// <param name="Table"></param>
        /// <param name="MatrixUID"></param>
        /// <param name="isFirst"></param>
        /// <returns></returns>
        private OrderLine AddLine_MatrixBindDataTable(SAPbouiCOM.Form oParentForm, OrderType ordertyp, string Table, string MatrixUID, bool isFirst = false)
        {
            SAPbouiCOM.DataTable dt_Rece = oParentForm.DataSources.DataTables.Item(Table);
            SAPbouiCOM.Matrix oMtx = oParentForm.Items.Item(MatrixUID).Specific;

            OrderLine line = B1Form_CreateCost.B1Order.Add(ordertyp);
            int LineId = 0;
            if (oMtx.RowCount > 0)
            {
                LineId = dt_Rece.GetValue("Index", dt_Rece.Rows.Count - 1);
                dt_Rece.Rows.Add();
            }
            if (dt_Rece.Rows.Count <= 0)
            {
                dt_Rece.Rows.Add();
            }
            dt_Rece.Rows.Offset = dt_Rece.Rows.Count - 1;
            dt_Rece.SetValue("Index", dt_Rece.Rows.Offset, LineId + 1);
            dt_Rece.SetValue("LineNum", dt_Rece.Rows.Offset, line.LineNum);
            dt_Rece.SetValue("DocEntry", dt_Rece.Rows.Offset, line.DocEntry);
            oMtx.AddRow();
            oMtx.SetLineData(oMtx.RowCount);
            return line;
        }
        private object GetMatrixLineId(SAPbouiCOM.Matrix oMtx)
        {
            int LineId = 0;
            if (oMtx.VisualRowCount == 0)
            {
                LineId = 1;
            }
            else
            {
                LineId = Convert.ToInt32(SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_f", oMtx.VisualRowCount));
            }
            return LineId;
        }

        #endregion
    }
}